package pw.farias.gpsgooglemaps;

//import android.app.Activity;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;










//import android.content.Intent;
import android.content.Context;
//import android.content.DialogInterface;
//import android.content.DialogInterface.OnClickListener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
//import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;

//import android.util.Log;
//import android.widget.TextView;


public class MapaActivity extends FragmentActivity{
	
	private TextView informacion=null;
	GoogleMap map;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.mapa);
		informacion = (TextView) this.findViewById(R.id.info);
		//boton para ver los datos en sqlite
//		View btnDB = findViewById(R.id.datosDB);
//		btnDB.setOnClickListener((android.view.View.OnClickListener) this);
		
		configGPS();
		
		map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
		map.setMyLocationEnabled(true);
//		
//		MarkerOptions marker1 = new MarkerOptions();
//		marker1.title("Marker 1");
//		marker1.snippet("Este marcador esta en Madrid");
//		
//		LatLng posicion1 = new LatLng(40.4378271,-3.6795367);
//		marker1.position(posicion1);
//		marker1.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
//		
//		map.addMarker(marker1);
		
	}
	
	private void configGPS(){
		LocationManager mLocationManager;
		LocationListener mLocationListener;
		
		mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		
		mLocationListener = new MyLocationListener();
		
		//(proveedror, tiempo, distancia)
		mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, mLocationListener);
		
	}
	

	
	private void UpdateScreen(Location location){
		
		//mostramos informacion en la pantalla del dispositivo
		
		Date fecha = new java.util.Date();
		Date hora = new java.util.Date();
		
//		long ahora = System.currentTimeMillis();
//		Date date = new Date(ahora);
		
		DateFormat f = new SimpleDateFormat("dd/MM/yy");
		DateFormat h = new SimpleDateFormat("HH:mm:ss");
		final String date = f.format(fecha);
		final String hour = h.format(hora);
		
//		informacion.setText("Latitud:"+String.valueOf(location.getLatitude())+"\n"+
//							"Longitud:"+String.valueOf(location.getLongitude())+"\n"+
//		"Fecha:"+fecha.getDate()+"/"+(fecha.getMonth()+1)+"/"+(fecha.getYear()+1900)+"\n"+
//							"hora:"+fecha.getHours()+":"+fecha.getMinutes());
		
		informacion.setText("Latitud: "+String.valueOf(location.getLatitude())+"\n"+
							"Longitud: "+String.valueOf(location.getLongitude())+"\n"+
							"Fecha: "+date+"\n"+
							"hora: "+hour);
		
		final String lati = String.valueOf(location.getLatitude());
		final String longi = String.valueOf(location.getLongitude());
		
		Handler_sqlite helper = new Handler_sqlite(this);
		helper.abrir();
		helper.insertaCoordenadas(lati, longi, date, hour );
		helper.cerrar();
		
		Thread nt = new Thread(){
			@Override
			public void run(){
				
				try{
					final String res;
					res=enviarPost(lati,longi,date,hour);
					
					runOnUiThread(new Runnable(){
						
						@Override
						 public void run(){
							Toast.makeText(MapaActivity.this, res, Toast.LENGTH_LONG).show();
						}
					});
				}catch(Exception e){
					
				}
			}
		};
		nt.start();
	}
	
	public String enviarPost(String latitud, String longitud, String fecha, String hora){
		HttpClient httpclient = new DefaultHttpClient();
		HttpContext localcontext = new BasicHttpContext();
		HttpPost httppost = new HttpPost("http://softtest.comuf.com/coordenadas/putGPS.php");
//		HttpPost httppost = new HttpPost("http://192.168.0.116:8080/appAndroid/coordenadas/putGPS.php");
		
		HttpResponse response = null;
			try{
			List<NameValuePair>  params = new ArrayList<NameValuePair>(3);
			params.add(new BasicNameValuePair("latitud", latitud));
			params.add(new BasicNameValuePair("longitud", longitud));
			params.add(new BasicNameValuePair("fecha", fecha));
			params.add(new BasicNameValuePair("hora", hora));
			
			httppost.setEntity(new UrlEncodedFormEntity(params));
			response = httpclient.execute(httppost, localcontext);
			
		}catch(Exception e){
			
		}
		return response.toString();
	}
	
	
	private class MyLocationListener implements LocationListener{

		@Override
		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			Log.d("gpsLocationBMS", "Latitud="+String.valueOf(location.getLatitude()));
			Log.d("gpsLocationBMS", "Longitud="+String.valueOf(location.getLongitude()));	
			UpdateScreen(location);
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			
		}
		
	}

//	public void onClick(View vista) {
//		// TODO Auto-generated method stub
//		if(vista.getId() == findViewById(R.id.datosDB).getId()){
//			Intent i = new Intent(this,datosActivity.class);
//			startActivity(i);
//			}
//	}
//
//	@Override
//	public void onClick(DialogInterface dialog, int which) {
//		// TODO Auto-generated method stub
//		
//	}

}
